<?php
/**
 * Manage user
 *
 * @author Mario Schillermann <info@rockit-flash.com>
 * @encoding UTF-8 äöüßÖÄÜ
 * @copyright © 2011 Mario Schillermann (info@rockit-flash.com)
 * @license GNU GPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
 * @package Page
 * @subpackage Index
 * @link $HeadURL$
 * @version SVN: $Id$
 * @phpVersion >=5
 * @todo
 */
class User_Model_Data
{
    /**
     * Get all user
     *
     * @return array users
     */
    static function get()
    {
        try {
            $file = 'home/default/rockitbos/userlist.dat';

            if(is_readable($file) === FALSE) {
                throw new Exception();
            }
            $handle = fopen ($file, "r");

            while (!feof($handle)) {
                $buffer = fgets($handle);
                $user = strstr($buffer, ':', true); // Ab PHP 5.3.0
                $users[$user] = $user;
            }
            fclose ($handle);

            return $users;
        } catch (Exception $e) {

            return FALSE;
        }
    }
    /**
     * Save new user
     *
     * @return boolean
     */
    static function save($values)
    {
        try {
            $username = $values['user'];
            $realm = "desktop";
            $password = md5($values['password']);
            $passwordForFile = md5("$username:$realm:$password");

            $file = 'home/default/rockitbos/userlist.dat';
            if(is_writable($file) === FALSE) {
                throw new Exception();
            }

            $handle = fopen($file, 'a');
            fwrite($handle, "\r\n");
            fwrite($handle, $username . ":" . $realm . ":" . $passwordForFile);
            fclose($handle);
            return TRUE;

        } catch (Exception $e) {

            return FALSE;
        }
    }
    /**
     * Delete user
     *
     * @return boolean
     */
    static function delete($selectUser)
    {
        try {
            $file = 'home/default/rockitbos/userlist.dat';
            if(is_writable($file) === FALSE) {
                throw new Exception();
            }

            $newContent = array();
            $content = file($file);
            foreach ($content as $row) {

                $user = strstr($row, ':', true); // Ab PHP 5.3.0

                if($user != $selectUser) {
                    $newContent[] = $row;
                }
            }

            $handle = fopen($file, 'w');

            foreach ($newContent as $row) {

                fwrite($handle, $row);
            }
            fclose($handle);

            return TRUE;

        } catch (Exception $e) {

            return FALSE;
        }
    }
}